﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.Mvc;
using System.Web.Routing;
using System.Threading;
using System.Globalization;
using VERKProjectHopur16.Models;
using VERKProjectHopur16.Helpers;

namespace VERKProjectHopur16
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        //XXX: Ask Dabs!
        protected void Session_Start(object sender, EventArgs a)
        {
            //We check and see if the user has selected a specific language
            //for the Websites framework and then tell the Framework to load that specific
            //language file, automatically (yeah, I know, makes no sense)

            //Preset to null
            if (Context.Session != null)
            {
                Context.Session["site-lang"] = "en";
            }
            else
            {
                Context.Session["site-lang"] = "en";
                throw new Exception("OMFG, SESSION IS GONE MAD");
            }
        }

        //XXX: This actually does this on every request, even for files
        //Which is what we were trying to do anyway... *cough*
        //XXX: Ask Dabs!
        protected void Application_PreRequestHandlerExecute(object sender, EventArgs a)
        {
            string x = "en";

            if (Context.Session == null)
            {
                return; //We're here because we didn't send any cookies to the server (CSS/JS/Image files)
            }
            else
            {
                if (Context.Session["site-lang"] != null)
                {
                    x = Context.Session["site-lang"].ToString();
                }
            }

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(x);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(x);
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);


            Context.Cache["LatestQA"] = new CacheUpdate().UpdateCacheQA();
            Context.Cache["LatestEvent"] = new CacheUpdate().UpdateCacheEvent();
        }
    }
}
